<?php
session_start();
require_once('inc_wtfaq.php');

if (isset($_GET['email']) && isset($_GET['token'])) {
	$query = "SELECT id,token FROM wtfaq_user WHERE email='".mysql_real_escape_string($_GET['email'])."'";
	$result = mysql_query($query);

	if (!$result) {
		$message  = 'Invalid query: ' . mysql_error() . "\n";
		$message .= 'Whole query: ' . $query;
		print '{"status":"error", "msg": "'.$message.'"}';
	}

	if ($row = mysql_fetch_assoc($result)) {
		if ($_GET['token'] == $row['token']) {
			$_SESSION['wtfaq']['UID'] = $row['id'];
			$_SESSION['wtfaq']['email'] = $_GET['email'];	

			$query = "SELECT id, title, location FROM wtfaq_wtfaq WHERE user_id='".$row['id']."'";
			$result = mysql_query($query);

			if (!$result) {
				$message  = 'Invalid query: ' . mysql_error() . "\n";
				$message .= 'Whole query: ' . $query;
				print '{"status":"error", "msg": "'.$message.'"}';
			}
			
			$wtfaqs = array();
			while ($rij = mysql_fetch_assoc($result)) {
				$wtfaqs[] = $rij;
			}
			
			
			print '{"status":"ok", "msg": "loggedIn", "wtfaqs":'.json_encode($wtfaqs).' }';
		}
		else
			print '{"status":"error", "msg": "invalid credentials"}';		
	}
	else {
		$query = sprintf("INSERT INTO wtfaq_user(email, token) VALUES ('%s','%s')",
					mysql_real_escape_string($_GET['email']),
					mysql_real_escape_string($_GET['token']));
	
		$result = mysql_query($query);	
		$_SESSION['wtfaq']['UID'] = mysql_insert_id();	
		$_SESSION['wtfaq']['email'] = $_GET['email'];	

		//var_dump($_SESSION['wtfaq']);	
		print '{ "status": "ok", "msg": "nieuwe user is ingelogd}';
	}
} //Dit is de nulde stap: controleren of het emailadres al bestaat
elseif (isset($_GET['email'])) {
	$query = "SELECT id FROM wtfaq_user WHERE email='".mysql_real_escape_string($_GET['email'])."'";
	$result = mysql_query($query);

	if (!$result) {
		$message  = 'Invalid query: ' . mysql_error() . "\n";
		$message .= 'Whole query: ' . $query;
		print '{"status":"error", "msg": "'.$message.'"}';
	}

	if ($row = mysql_fetch_assoc($result)) 
		print '{"status":"ok", "msg": "exists"}';
	else
		print '{"status":"ok", "msg": "new"}';
}
else // in alle andere gevallen is het niet oke
		print '{"status":"error", "msg": "bla"}';
?>